<template>
  <div>
    <span v-if="labelOnly">{{label}}</span>
    <tree-select
      v-else
      ref="treeSelect"
      @treeSelect="handleSelect"
      @cancelSelect="handleCancelSelect"
      :placeholder="placeholder"
      :customLabel="true"
      :labelOnly="labelOnly"
      :disableBranchNodes="true"
      :selectStyle="selectStyle"
      :options="deptTreeData"
      :selectValue="value"
      :multiple="multiple"
      :disabled="disabled"
      :clearable="clearable"
      @valueChange="valueChange"
    />
  </div>
</template>

<script>
import TreeSelect from '@/components/ETreeSelect'
import { getDeptPositionTree } from '@/api/department'

export default {
  name: 'DeptPositionS',
  components: { TreeSelect },
  props: {
    labelOnly: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    selectValue: [String, Array], // 多选时为Array
    clearable: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: undefined
    },
    multiple: {
      type: Boolean,
      default() {
        return false
      }
    },
    selectStyle: {
      type: Object,
      default: () => {
        return {}
      }
    }
    // selectValue: [String, Array] // 多选时为Array
  },
  watch: {
    selectValue(n, o) {
      if (n !== o) {
        this.value = n
      }
    }
  },
  created() {
    this.value = this.selectValue
  },
  mounted() {
    getDeptPositionTree().then(res => {
      const arr = res.data
      this.deptTreeData = this.handleData(res.data)
    })
  },
  data() {
    return {
      deptTreeData: [],
      value: undefined,
      label: '',
      node: null
    }
  },
  methods: {
    handleData(arr, parent) {
      arr.map(v => {
        v.parentLabel = parent ? parent.label : ''
        v.childLabel = v.title.replace('-' + v.parentLabel, '')
        v.id = v.key
        v.label = v.childLabel
        v.customLabel = v.parentLabel ? v.parentLabel + '-' + v.childLabel : v.childLabel
        if (v.children && v.children.length > 0) {
          this.handleData(v.children, v)
        } else {
          if (v.key.split('-').length === 1) {
            v.isDisabled = true // 设置部门禁止选择
          }
          delete v.children
        }
      })
      return arr
    },
    reset() {
      this.$refs.treeSelect.reset()
    },
    handleSelect(node) {
      if (node.id.split('-').length === 1) {
        this.$nextTick(() => {
          this.reset()
        })
        this.$message.error('请选择岗位')
        return false
      } else {
        this.$emit('select', node)
      }
    },
    handleCancelSelect(node) {
      this.node = null
      this.$emit('cancelSelect', node)
    },
    valueChange(value, valueDetail, node) {
      this.$emit('valueChange', value, valueDetail, node)
    }
  }
}
</script>
